﻿using System;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;

namespace ProjetoFase2
{
    public partial class ListenForm : Form
    {
        private int port;
        private TcpListener listener;
        private Socket traineeSocket;
        private Thread listenThread;
        private NetworkStream stream;
        private DataSet traineeDataSet;

        public ListenForm(string ip, int port)
        {
            InitializeComponent();

            this.port = port;

            listener = new TcpListener(this.port);
            listener.Start();

            listenThread = new Thread(new ThreadStart(Listen));
            listenThread.Start();
        }

        private void Listen()
        {
            ServerInteraction servInt = new ServerInteraction(null, 0);
            traineeSocket = listener.AcceptSocket();

            if (traineeSocket.Connected)
            {
                stream = new NetworkStream(traineeSocket);
                traineeDataSet = servInt.readDataSet(stream);
                bindControls();
            }
        }

        private void bindControls()
        {


        }

        private void menuClose_Click(object sender, EventArgs e)
        {
            listener.Stop();
            this.Close();
        }

        private void btnSync_Click(object sender, EventArgs e)
        {
            ServerInteraction servInt = new ServerInteraction(null, 0);

            if (traineeSocket.Connected)
            {
                // send data back to trainee
                traineeDataSet.AcceptChanges();
                servInt.writeDataSet(stream, traineeDataSet);
            }
        }
    }
}